import { defineStore } from 'pinia'
import { getCache, setCache, removeCache } from '@/utils/cache'
import { GetUserInfoApi, LoginApi, GetBalanceApi } from '@/apis/user'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: {},
    token: 'admin-token',
    virtualToken: '',
    siteConfig: {}
  }),
  getters: {
    getToken: (state) => {
      if (state.token) return state.token
      const token = getCache('token')
      state.token = token
      return token
    },
    getVirtualToken: (state) => {
      if (state.virtualToken) return state.virtualToken
      const virtualToken = getCache('virtualToken')
      state.virtualToken = virtualToken
      return virtualToken
    },
    getUserInfo: (state) => {
      if (state.userInfo?.nickname) return state.userInfo
      const userInfo = getCache('userInfo')
      state.userInfo = userInfo
      return userInfo
    },
    getSiteConfig: (state) => {
      if (state.siteConfig?.rate) return state.siteConfig
      const siteConfig = getCache('siteConfig')
      state.siteConfig = siteConfig
      return siteConfig
    }
  },
  actions: {
    async refreshBanlce() {
      const data = await GetBalanceApi()
      this.userInfo.balance = data
    },
    setToken(token) {
      this.token = token
      setCache('token', token, true)
    },
    setVirtualToken(virtualToken) {
      this.virtualToken = virtualToken
      setCache('virtualToken', virtualToken, true)
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      setCache('userInfo', userInfo, true)
    },
    setSiteConfig(siteConfig) {
      this.siteConfig = siteConfig
      setCache('siteConfig', siteConfig, true)
    },
    async login(username, password, code, google) {
      // 清除虚拟登录的TOKEN
      removeCache('virtualToken')
      const { userInfo, siteConfig } = await LoginApi(username, password, code, google)
      this.setToken(userInfo.token)
      this.setUserInfo(userInfo)
      this.setSiteConfig(siteConfig)
      return userInfo
    },
    async xnLogin(token: string) {
      // 清除正常登录的TOKEN
      removeCache('token')
      this.setVirtualToken(token)
      const { userInfo, siteConfig } = await this.getUserInfoAction()
      this.setSiteConfig(siteConfig)
      this.setUserInfo(userInfo)
      return userInfo
    },
    async getUserInfoAction() {
      const data = await GetUserInfoApi()
      return { userInfo: data.userInfo, siteConfig: data.siteConfig }
    },
    logout() {
      removeCache('token')
      removeCache('userInfo')
      removeCache('siteConfig')

      this.setToken(null)
      this.setUserInfo(null)
      this.setSiteConfig(null)

      router.push('/login')
    }
  }
})
